package com.yungu.swift.demo.mq.controller;

import com.yungu.swift.demo.mq.model.LogDto;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class LoginController {

    @Value("${log.queue.name}")
    private String logQueue;

    @Value("${log.exchange.name}")
    private String logExchange;

    @Value("${log.routing.key.name}")
    private String logRoutingKey;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping(value = "/login")
    public void login() {
        //执行登录逻辑
        //...
        //异步写用户日志
        LogDto logDto = new LogDto();
        logDto.setUuid(StringUtils.buildUUID());
        logDto.setSystemName("demo");
        logDto.setModuleName("mqTest");
        logDto.setOperation("login");
        logDto.setCreateOn(new Date());
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setExchange(logExchange);
        rabbitTemplate.setRoutingKey(logRoutingKey);
        Message message = MessageBuilder.withBody(JsonUtils.toJSONBytes(logDto)).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
        message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, MessageProperties.CONTENT_TYPE_JSON);
        rabbitTemplate.convertAndSend(message);
    }


    /**
     * 优先选择这种方式
     */
    @RequestMapping(value = "/loginLog")
    public void loginLog() {
        //执行登录逻辑
        //...
        //异步写用户日志
        LogDto logDto = new LogDto();
        logDto.setUuid(StringUtils.buildUUID());
        logDto.setSystemName("Demo");
        logDto.setModuleName("loginTest");
        logDto.setOperation("loginLog");
        logDto.setCreateOn(new Date());
        rabbitTemplate.convertAndSend("loginLogExchange", "loginLog.123", logDto);
    }
}
